package com.bangdao.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chen
 * @create 2021-01-03
 */

/**
 * 使用Condition对象
 * condition.await()等待
 * condition.signalAll()唤醒
 */
public class ConditionDemo {
    public static void main(String[] args) {
        ShareDataTwo dataTwo = new ShareDataTwo();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    dataTwo.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "a").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    dataTwo.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "b").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    dataTwo.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "c").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    dataTwo.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "d").start();
    }

}

class ShareDataTwo {
    private Integer num = 0;
    // 初始化lock锁
    private ReentrantLock lock = new ReentrantLock();
    // 初始化condition对象
    Condition condition = lock.newCondition();

    public void incr() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (num != 0) {
                condition.await();
            }
            //干活
            num++;
            System.out.println(Thread.currentThread().getName() + ":" + num);
            //通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decr() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (num != 1) {
                condition.await();
            }
            //干活
            num--;
            System.out.println(Thread.currentThread().getName() + ":" + num);
            //通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}